<?php

App::uses('AppHelper', 'View/Helper');

class GeonameInputHelper extends AppHelper{
	
	var $helpers = array('Html');
	
	var $country_id = 'country_id';
	var $country_id_hidden = 'country_id_hidden';
	var $state_id = 'state_id';
	var $state_id_hidden = 'state_id_hidden';
	var $city_id = 'city_id';
	var $city_id_hidden = 'city_id_hidden';
	
	public function config($array){
		foreach ($array as $key=>$item){
			$this->$key = $item;
		}
	}
	
	function getLanguage(){
		//echo Configure::read('Config.language');
		if(Configure::read('Config.language') == 'pt-br')
			$lang = 'pt';
		else $lang = Configure::read('Config.language');
		return $lang;
	}
	
	public function begin(){
		$url = $this->Html->url('/', true);
		echo 
		
		"<script type=text/javascript>
				
		jQuery(function(){
		
		$(':input#$this->country_id_hidden').hide();
		$(':input#$this->state_id_hidden').hide();
		$(':input#$this->city_id_hidden').hide();
		if($(':input#$this->country_id_hidden').val() == ''){
			$(':input#$this->state_id').attr('disabled', true);
			$(':input#$this->state_id_hidden').attr('disabled', true);
		}
		if($(':input#$this->state_id_hidden').val() == ''){
			$(':input#$this->city_id').attr('disabled', true);
			$(':input#$this->city_id_hidden').attr('disabled', true);
		}	

		$.ajax({
			url: '".$url."geonames/geonames/paises',
			dataType: 'json',
			beforeSend: function(){
				$('#$this->country_id option').remove();
				$('#$this->country_id').append($('<option>').text('".__('Carregando...')."').attr('value', 0));
			},
			success: function(data){
				$('#$this->country_id option').remove();
				$('#$this->country_id').append($('<option>').text('".__('Escolha um país')."').attr('value', 0));
				$.each(data, function(i, item){
					$('#$this->country_id').append($('<option>').text(item.countryName).attr('value', item.geonameId));
				});
				var pais = $('#$this->country_id_hidden').text();
				if(pais != ''){
					$('option[value=\"'+pais+'\"]').attr('selected', true);
					changeState();
				}				
			}
		});
		
		$('#$this->country_id').change(function(){
			changeState();
			$('#$this->city_id option').remove();
			$('#$this->city_id').append($('<option>').text('".__('Escolha um estado primeiro')."').attr('value', 0));
		});
		
		$('#$this->state_id').change(function(){
			changeCity();
		});
		
		function changeState(){
			$.ajax({
				url: '".$url."geonames/geonames/estados?parentId='+$(':input#$this->country_id').val(),
				dataType: 'json',
				beforeSend: function(){
					$('#$this->state_id option').remove();
					$('#$this->state_id').append($('<option>').text('".__('Carregando...')."').attr('value', 0));
				},
				success: function(data){
					$('#$this->state_id option').remove();
					$('#$this->state_id').append($('<option>').text('".__('Escolha um estado')."').attr('value', 0));
					$.each(data, function(i, item){
						$('#$this->state_id').append($('<option>').text(item.name).attr('value', item.geonameId));
					});
					var estado = $('#$this->state_id_hidden').text();
					if(estado != ''){
						$('option[value=\"'+estado+'\"]').attr('selected', true);
						changeCity();
					}
				}
			});
		}
		
		function changeCity(){
			$.ajax({
				url: '".$url."geonames/geonames/cidades?parentId='+$(':input#$this->state_id').val(),
				dataType: 'json',
				beforeSend: function(){
					$('#$this->city_id option').remove();
					$('#$this->city_id').append($('<option>').text('".__('Carregando...')."').attr('value', 0));
				},
				success: function(data){
					$('#$this->city_id option').remove();
					$('#$this->city_id').append($('<option>').text('".__('Escolha uma cidade')."').attr('value', 0));
					$.each(data, function(i, item){
						$('#$this->city_id').append($('<option>').text(item.name).attr('value', item.geonameId));
					});
					var cidade = $('#$this->city_id_hidden').text();
					if(cidade != '')
						$('option[value=\"'+cidade+'\"]').attr('selected', true);
				}
			});
		}
			
		$(':input#$this->city_id').typeahead({
			source: function(query, process) {
				objects = [];
				map = {};
				return $.get(
					'".$url."geonames/geonames/cidades',
					{ query: query, parentId: $(':input#$this->state_id_hidden').val() },
					function (data) {
						dados = JSON.parse(data);
						$.each(dados, function(i, object) {
							map[object.name] = object;
							objects.push(object.name);
						});
						return process(objects);
					}
				);
		    },
		    updater: function(item) {
		        $(':input#$this->city_id_hidden').val(map[item].geonameId);
		        return item;
		    }
		}); 
		});
		</script>		
		";
	
	}
	
	public function findCountryName($geonameId){
		$this->Pais = ClassRegistry::init('Geonames.Pais');
		$pais = $this->Pais->find('first', array('conditions'=>array('geonameId'=>$geonameId, 'language'=>$this->getLanguage())));
		if(isset($pais['Pais']['countryName']))
			return ($pais['Pais']['countryName']);
		else return '';
	}
	
	public function findStateName($geonameId){
		$this->Regiao = ClassRegistry::init('Geonames.RegiaoAdministrativa');
		$pais = $this->Regiao->find('first', array('conditions'=>array('geonameId'=>$geonameId, 'language'=>$this->getLanguage())));
		if(isset($pais['RegiaoAdministrativa']['name']))
			return ($pais['RegiaoAdministrativa']['name']);
		else return '';
	}
	
	public function findCityName($geonameId){
		$this->Cidade = ClassRegistry::init('Geonames.Cidade');
		$pais = $this->Cidade->find('first', array('conditions'=>array('geonameId'=>$geonameId, 'language'=>$this->getLanguage())));
		if(isset($pais['Cidade']['name']))
			return ($pais['Cidade']['name']);
		else return '';
	}
	
}

?>
